$(function(){/*
	function CountDown(callback){
		this.intervalHandle = null
		this.interval = 1000;
		this.number = 0;
		this.callback = callback;
	}

	CountDown.prototype = {
		tick : function(number){
			var self = this;
			this.number = number;

			if(this.intervalHandle != null){
				window.clearInterval(this.intervalHandle);
			}

			this.intervalHandle = window.setInterval(function(){
				self.number--;

				if(self.number <= 0){
					window.clearInterval(self.intervalHandle);
					return;
				}else{
					self.callback();
				}
			}, this.interval);
		},
		clear : function(){
			window.clearInterval(this.intervalHandle);
		}
	};

	var cd = new CountDown(function(){
		$('span.tick').html(this.number);
	});

	function parse(template,object){
		return template.replace(/\${(\w+)}/g,function(){
			return object[arguments[1]];
		});
	}

	function ip2long(ip){
		var segments = ip.split('.'),
		result = 0;
		for(var i=3;i>=0;i--){
			result += parseInt(segments[3-i])*Math.pow(256,i);
		}
		return result;
	}

	function ip2long_bak(ip){
		var segments = ip.split('.'),
		result = 0;

		for(var i=0; i < segments.length; i++){
			result += (parseInt(segments[i]) << ((3 - i)*8));
		}

		return result;
	}

	function long2ip(number){
		var ip = [];
		for(var i=3;i>=0;i--){
			var ipItem = parseInt(number/Math.pow(256, i));
			ip.push(ipItem);
			number -= ipItem * Math.pow(256,i);
		}
		return ip.join(".");
	}

	function ajax(o){
		var obj = {};
		obj.url = o.url;
		obj.dataType = o.dataType || 'json';
		obj.type = o.type || 'get';
		obj.data = o.data || {};
		obj.success = function(response){
			switch(response.status){
				case 1:
					alert(response.message);
					break;
				case 0:
					if(response.message.length){
						alert(response.message);
					}
					o.success(response.data);
					break;
			}
		}

		$.ajax(obj);
	}

	function prefixZero(number){
		return parseInt(number) > 9?number:('0'+number);
	}

	function dateFormat(time,format){
		var date = time>0?new Date(time):new Date(),
		template = format || 'Y-m-d H:i:s',
		result = '';
		result = template.replace('Y',prefixZero(date.getFullYear()));
		result = result.replace('m',prefixZero((date.getMonth()+1)));
		result = result.replace('d',prefixZero(date.getDate()));
		result = result.replace('H',prefixZero(date.getHours()));
		result = result.replace('i',prefixZero(date.getMinutes()));
		result = result.replace('s',prefixZero(date.getSeconds()));
		return result;
	}

	function setCookie(name,value,expire){
		var now = new Date();
		now.setDate(now.getDate() + expire);
		document.cookie = name+'='+escape(value)+(expire == null?'':';expires='+now.toGMTString());
	}

	function getCookie(name){
		if(document.cookie.length > 0){
			start = document.cookie.indexOf(name + '=');

			if(start != -1){
				start = start + name.length + 1;
				end = document.cookie.indexOf(';',start);
				if(end === -1){
					end = document.cookie.length - start;
				}
				return document.cookie.substring(start,end);
			}
		}
		return '';
	}

	var INIT_INTERVAL = 3000;
	var lastTime = 0,
	interval = INIT_INTERVAL,
	tick = null,
	liTemplate = '<li><span class="name">${from}</span><span class="datetime">${date}</span><br/>${content}</li>';

	$('form').submit(function(){
		var content = $(this).find('input.content').val().replace(/^\s+|\s+$/g,'');
		if(content == ''){
			alert('pls enter content.');
			$(this).find('input.content').trigger('focus');
			return false;
		}

		if(content.length > 500 ){
			alert('content is too long.');
			return false;
		}

		ajax({
			url : $(this).attr('action'),
			type: $(this).attr('method'),
			data: $(this).serialize(),
			success: function(){
				interval = INIT_INTERVAL;
				receive();
				setCookie('username',name);
			}
		});

		$(this).find('input.content').val('');

		return false;
	});

	function rend(records){
		if(records.length > 0){
			var lis = [];
			$(records).each(function(index,item){
				item.date = dateFormat(item.created_at * 1000);
				lis.push(parse(liTemplate,item));

			});
			$('ul.chat-content').append(lis.join(''));
		}
	}

	function history(){
		ajax({
			url : SITE_URL + '/index.php?chat/history',
			data: {
				lastTime : lastTime
			},
			dataType: 'json',
			success: function(data){
				$('table.chat-history').show();
				if(data.records.length > 0){
					var html = [];
					$(data.records).each(function(index, item){
						item.ip = long2ip(item.ip);
						item.created_at = dateFormat(item.created_at*1000);
						html.push(parse("<tr><td>${name}</td><td>${ip}</td><td>${content}</td><td>${created_at}</td></tr>",item));
					});
					$('table.chat-history tbody').html(html.join(''));
				}else{
					$('table.chat-history tbody tr td').html('目前没有聊天历史记录');
				}
			}
		});
	}

	function receive(){
		if(tick != null){
			clearInterval(tick);
		}

		$('div.info img.ajax-loader').show();

		ajax({
			url : SITE_URL + '/index.php?chat/receive',
			data: {
				lastTime : lastTime
			},
			dataType: 'json',
			success: function(data){
				if(data.records.length > 0){
					lastTime = data.time;
					interval = INIT_INTERVAL;
					rend(data.records);
				}else{
					interval += (interval < 15000)?1000:0;
				}

				cd.tick(parseInt(interval/1000));

				tick = setTimeout(function(){
					receive();
				},interval);

				$('div.info img.ajax-loader').hide();

				$('div.chat-content-wrap').scrollTop($('ul.chat-content').height() - $('div.chat-content-wrap').height());
			}
		});
	}

	$('a.clear').click(function(event){
		$('ul.chat-contnet li').remove();
		if(event.ctrlKey){
			ajax({
				url : SITE_URL + '/index.php?chat/clear'
			});
		}
		return false;
	});

	$('div.info img.ajax-loader').hide();

	receive();

	$('a.open-history').click(function(){
		history();
		return false;
	});

	$('a.close-history').click(function(){
		$('table.chat-history tbody').html('<tr><td colspan="4" style="text-align:center">关闭状态</td></tr>');
		$('table.chat-history').hide();
		return false;
	});

	$('a.stop-auto-receive').click(function(){
		if(tick != null){
			clearInterval(tick);
		}
		return false;
	});

	$('a.start-auto-receive').click(function(){
		if(tick != null){
			clearInterval(tick);
		}
		receive();
		return false;
	});

	var username = getCookie('username');

	$('input.name').val(username == ''?'您的昵称！':username);


	function encrypt(string,secret){
		if(typeof secret !== 'sting'){
			secret = secret.toString();
		}

		var result =  [];

		if(string.length > 0){
			for(var i=0;i< string.length;i++){
				var code = string.charCodeAt(i);
				if(secret.length > 0){
					for(var j=0;j<secret.length;j++){
						code ^= secret.charCodeAt(j);
					}
				}
				result.push(String.fromCharCode(code));
			}
		}

		return result.join('');
	}



	function decrypt(string,secret){
		if(typeof secret !== 'sting'){
			secret = secret.toString();
		}

		var result = [];

		if(string.length > 0){
			for(var i = 0;i < string.length;i++){
				var code = string.charCodeAt(i);
				if(secret.length > 0){
					for(var j=secret.length;j>0;j--){
						code ^= secret.charCodeAt(j-1);
					}
				}
				result.push(String.fromCharCode(code));
			}

		}
		return result.join('');
	}
	*/
	var titleTime = 0;
	var msg = 'nacy来消息啦……';
	var l = msg.length;
	var titleInterval = window.setInterval(function(){
		titleTime++;
		
		$('title').html(msg.substr(titleTime % l));
		
		if(titleTime == 50){
			window.clearInterval(titleInterval);
		}
	},500);
	
});